package com.dkt.android.mvp.presenter

import com.dkt.android.api.UserApiService
import com.dkt.android.base.BaseCallSubscriber
import com.dkt.android.base.BasePresenterImpl
import com.dkt.android.base.BaseRsps
import com.dkt.android.mvp.contract.LoginContract
import com.dkt.android.mvp.contract.UserContractImpl
import com.dkt.android.mvp.model.BackUserInfo
import com.dkt.android.mvp.model.LoginInfo
import retrofit2.Response

/**
 * @author: dtb
 * @email: wendaoyuqin1@gmail.com
 * @createTime: 19-3-14下午2:27
 */
class LoginPresenter : BasePresenterImpl(), LoginContract.Presenter {


    private fun showError(view: LoginContract.LoginView, msg: String) {
        showError(view, arrayOf(msg))
    }

    private fun showError(view: LoginContract.LoginView, msg: Array<String>?) {
        view.equalToFunc {
            it.showErr(msg)
        }
    }
    override fun toLogin(view: LoginContract.LoginView, info: LoginInfo) {
        if (!UserInfoParity.parityUserInfo(info) {
                showError(view, it)
            }) {
            view.equalToFunc {
                view.proDialogDismiss()
            }
            return
        }

        handler.createNetWork<Response<BaseRsps<BackUserInfo?>>>("login")
            ?.apply {
                observable = UserApiService.login(info)
                disposable = object : BaseCallSubscriber<BackUserInfo?>() {
                    override fun onStart() {
                        super.onStart()
                        view.showProgressDialog(null)
                    }

                    override fun onSuccess(baseRsps: BaseRsps<BackUserInfo?>?) {
                        view.equalToFunc {
                            if (baseRsps?.rc=="S"
                            ) {
                                UserContractImpl.updateUserDate(baseRsps.data)
                                view.loginSuccess()
                            } else {
                                view.showErr(arrayOf("登陆失败"))
                            }
                        }
                    }

                    override fun onError(code: Int?, baseRsps: BaseRsps<BackUserInfo?>?) {
                        showError(view, baseRsps?.msg)
                    }

                    override fun onEnd() {
                        view.equalToFunc {
                            view.proDialogDismiss()
                        }
                    }
                }
            }?.start()
    }
}